import { useState, useRef, useEffect } from "react";
import { Tooltip, Space, Button, Popconfirm, message, Modal } from "antd";
import {
  PauseCircleOutlined,
  CaretRightOutlined,
  DeleteOutlined,
  StopOutlined,
  InfoCircleOutlined,
} from "@ant-design/icons";
import useProcessDefOptionsHooks from "./ProcessDefOptionsHooks.jsx";
import CamundaAPI from "@/api/CamundaApi.js";

import useModalHooks from "./ModalHooks";

function useProcessInstanceList() {
  // loading
  const [loading, setLoading] = useState(false);
  // 表格数据
  const [tableData, setTableData] = useState({
    list: [], // 数据列表
  });

  // 搜索关键字
  const [keyWords, setKeyWords] = useState("");
  const [procDefId, setProcDefId] = useState("");
  // 排序信息 TODO
  const sortData = useRef({
    sortField: "procinst.start_time_",
    sortOrder: "descend",
  });

  // 分页数据 - 用于同步计算
  const paginationData = useRef({
    current: 1, // 当前页数
    pageSize: 10, // 页面显示的条目数
    total: 0, // 记录条目总数
    pageSizeOptions: [5, 10, 15, 20, 30, 50, 100], // 条目数选项
  });

  const columnRender = (v) => {
    return (
      <Tooltip placement="topLeft" title={v}>
        {v}
      </Tooltip>
    );
  };

  // 表格字段
  const columnsData = useRef([
    {
      title: "Business Key",
      dataIndex: "businessKey",
      key: "procinst.business_key_",
      width: 150,
      fixed: "left",
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "Process Instance Id",
      dataIndex: "processInstanceId",
      key: "procinst.id_",
      fixed: "left",
      width: 200,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "State",
      dataIndex: "state",
      key: "procinst.state_",
      fixed: "left",
      width: 100,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },

    {
      title: "DefKey",
      dataIndex: "defKey",
      key: "def.key_",
      fixed: "left",
      width: 200,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "DefName",
      dataIndex: "defName",
      key: "def.name_",
      width: 150,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "DefVersion",
      dataIndex: "defVersion",
      key: "def.version_",
      width: 150,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "Start Time",
      dataIndex: "processInstanceStartTime",
      key: "procinst.start_time_",
      width: 150,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "End Time",
      dataIndex: "processInstanceEndTime",
      key: "procinst.end_time_",
      width: 150,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "Operate",
      dataIndex: "operate",
      key: "operate",
      fixed: "right",
      align: "center",
      width: 180,
      render: (text, record) => {
        return (
          <div>
            <Space>
              <Popconfirm
                placement="topLeft"
                title="Mark sure suspend this process ?"
                onConfirm={() => {
                  suspendsProcessInstance(record.processInstanceId);
                }}
                okText="Yes"
                cancelText="No"
              >
                <Button
                  type="dashed"
                  icon={<PauseCircleOutlined />}
                  disabled={
                    record.state === "INTERNALLY_TERMINATED" ||
                    record.state === "COMPLETED" ||
                    record.state === "SUSPENDED"
                  }
                ></Button>
              </Popconfirm>
              <Button
                type="dashed"
                icon={<CaretRightOutlined />}
                disabled={
                  record.state === "INTERNALLY_TERMINATED" ||
                  record.state === "COMPLETED" ||
                  record.state === "ACTIVE"
                }
                onClick={() => {
                  activateProcessInstance(record.processInstanceId);
                }}
              ></Button>

              <Popconfirm
                placement="topLeft"
                title="Mark sure delete ?"
                onConfirm={() => {
                  cancelProcessInstance(record.processInstanceId);
                }}
                okText="Yes"
                cancelText="No"
              >
                <Button
                  type="dashed"
                  icon={<DeleteOutlined />}
                  disabled={
                    record.state === "INTERNALLY_TERMINATED" ||
                    record.state === "COMPLETED"
                  }
                ></Button>
              </Popconfirm>

              <Button
                type="dashed"
                icon={<InfoCircleOutlined />}
                onClick={() => {
                  setProcInstId(record.processInstanceId);
                  openModalForProcInst();
                }}
              ></Button>
            </Space>
          </div>
        );
      },
    },
  ]);

  // 搜索数据
  const search = function (clearPage) {
    // 初始化字段排序信息
    initColumnSortInfo();
    // 打开loading
    setLoading(true);

    // 清除分页
    if (clearPage) {
      paginationData.current.current = 1;
    }

    // 创建处理分页和排序
    let params = {
      keyWords,
      procDefId,
      current: paginationData.current.current,
      pageSize: paginationData.current.pageSize,
    };

    if (sortData.current.sortOrder) {
      params = {
        ...params,
        sortField: sortData.current.sortField,
        sortOrder: sortData.current.sortOrder.replace("end", ""),
      };
    }

    console.log("search:", params);

    CamundaAPI.queryProcessInstancePage(params)
      .then((r) => {
        console.log(r);

        // 设置记录总数
        paginationData.current = {
          ...paginationData.current,
          total: r.result.total,
        };

        // 排序显示
        columnsData.current;

        // 设置数据列表内容
        setTableData({
          ...tableData,
          list: r.result.list,
        });

        // 关闭loading
        setLoading(false);
      })
      .catch(() => {
        // 关闭loading
        setLoading(false);
      });
  };

  // 初始化字段的排序信息 sortField:字段名   sortOrder:排序(ascend,descend,undefined)
  function initColumnSortInfo() {
    columnsData.current.forEach((item) => {
      delete item.sortOrder;
      if (sortData.current.sortOrder) {
        if (item.key === sortData.current.sortField) {
          item.sortOrder = sortData.current.sortOrder;
        }
      }
    });
  }

  const onPaginationChange = function (page, pageSize) {
    console.log(`pageChange[currentPage:${page},pageSize:${pageSize}]`);
    paginationData.current = {
      ...paginationData.current,
      current: page,
      pageSize,
    };
    // 查询数据
    search();
  };

  const onTableChange = function (pagination, filters, sorter) {
    console.log("sortChange", sorter);

    if (sorter.column) {
      sortData.current = {
        ...sortData.current,
        sortField: sorter.column.key,
        sortOrder: sorter.order,
      };
    } else {
      sortData.current = {
        ...sortData.current,
        sortOrder: "",
      };
    }
    search();
  };

  function suspendsProcessInstance(processInstanceId) {
    CamundaAPI.suspendsProcessInstance(processInstanceId).then((r) => {
      search();
      Modal.success({
        title: "Process Be Suspended Successful",
        centered: true,
        okText: "确认",
        onOk() {
          // 弹出登录弹框
        },
      });
    });
  }

  function activateProcessInstance(processInstanceId) {
    CamundaAPI.activateProcessInstance(processInstanceId).then((r) => {
      search();
      Modal.success({
        title: "Process Be Actived Successful",
        centered: true,
        okText: "确认",
        onOk() {
          // 弹出登录弹框
        },
      });
    });
  }

  function cancelProcessInstance(processInstanceId) {
    CamundaAPI.cancelProcessInstance(processInstanceId).then((r) => {
      search();
      Modal.success({
        title: "Process Be Cancel Successful",
        centered: true,
        okText: "确认",
        onOk() {
          // 弹出登录弹框
        },
      });
    });
  }

  // onComponentDidMounted
  useEffect(() => {
    search();
  }, []);

  const { processDefList, onProcessDefSearch } = useProcessDefOptionsHooks();

  // ========================== 开启流程modal ============================
  // 开启流程modal
  const [startProcessModalVisible, setStartProcessModalVisible] =
    useState(false);

  // 流程定义id
  const [processDefId, setProcessDefId] = useState("");

  function openStartProcessModal(processDefId) {
    setStartProcessModalVisible(true);
  }

  function closeStartProcessModal() {
    setStartProcessModalVisible(false);
  }

  // ========================== 流程实例详情modal ============================

  const {
    modalVisible: modalVisibleForProcInst,
    setModalVisible: setModalVisibleForProcInst,
    openModal: openModalForProcInst,
    closeModal: closeModalForProcInst,
  } = useModalHooks();

  // ========================== procInstId ==================================

  const [procInstId, setProcInstId] = useState("");
  return {
    procInstId,
    setProcInstId,
    modalVisibleForProcInst,
    setModalVisibleForProcInst,
    openModalForProcInst,
    closeModalForProcInst,

    setStartProcessModalVisible,
    startProcessModalVisible,
    openStartProcessModal,
    closeStartProcessModal,

    setKeyWords,
    loading,
    setLoading,
    tableData,
    paginationData,
    search,
    onPaginationChange,
    onTableChange,
    columnsData,

    processDefList,
    onProcessDefSearch,
    setProcDefId,
  };
}

export default useProcessInstanceList;
